package com.wisemoresystem.seal.util.abchinaFinger.usap;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.wisemoresystem.seal.util.abchinaFinger.common.AbcCoreCfg;

public class UsapTrans {
	private static Log log = LogFactory.getLog(UsapTrans.class);
	private CloseableHttpClient client = null;
	private HttpPost httpPost = null;
	private AbcCoreCfg abcConfig = null;

	public UsapTrans(AbcCoreCfg abcConfig) {
		this.abcConfig = abcConfig;
	}

	public UsapTrans() {
		abcConfig = new AbcCoreCfg("USAP");
	}

	private String convTeller(String szTeller) {
		String teller = null;
		if (szTeller.length() == 9)
			teller = "B" + szTeller; // BoEing柜员
		else if (szTeller.length() == 10)
			teller = szTeller.substring(0, 2) + szTeller.substring(6);// 普通柜员，去掉行号部分
		else
			teller = szTeller;

		return teller;
	}

	private String getUsapRespcode(String xmlDoc) {
		log.debug("[" + xmlDoc + "]");
		String szResult = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		StringReader sRead = new StringReader(xmlDoc);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(sRead);
		try {
			DocumentBuilder builder = dbf.newDocumentBuilder();
			Document doc = builder.parse(source);
			NodeList nl = doc.getDocumentElement().getElementsByTagName(
					"BusinessStatus");
			if (nl.getLength() > 0)
				szResult = nl.item(0).getTextContent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (szResult.equals("SSO_7"))
			szResult = "SUCCESS.认证成功";
		else if (szResult.equals("9503"))
			szResult = "FAIL.指纹匹配错误！";
		else if (szResult.equals("UA_5001"))
			szResult = "FAIL.帐号输入错误！";
		else if (szResult.equals("9514"))
			szResult = "FAIL.USAP中帐号已被锁定！";
		else if (szResult.equals("UA_5013") || szResult.equals("9505"))
			szResult = "FAIL.用户名或密码错！";
		else if (szResult.equals("UA_5100"))
			szResult = "FAIL.USAP中无对应指纹数据！";
		else if (szResult != null)
			szResult = "FAIL." + szResult;

		return szResult;
	}

	public String fingerCheck(String szTeller, String feature,
			String szDevFactoryID) {
		String szResult = "";
		client = HttpClients.createDefault();
		httpPost = new HttpPost(abcConfig.getServicename());
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("ProtocalVersion", "V1.0.0"));
		nvps.add(new BasicNameValuePair("ProcessCode", "108"));
		nvps.add(new BasicNameValuePair("UserCode", convTeller(szTeller)));
		nvps.add(new BasicNameValuePair("AuthenticationType", "3"));
		nvps.add(new BasicNameValuePair("Token", feature));
		nvps.add(new BasicNameValuePair("ClientUnique", abcConfig.getProgram()));
		nvps.add(new BasicNameValuePair("RandomCode", ""));
		nvps.add(new BasicNameValuePair("ForceLogin", "false"));
		nvps.add(new BasicNameValuePair("IdentitySN", ""));
		nvps.add(new BasicNameValuePair("CertSerial", ""));
		nvps.add(new BasicNameValuePair("ProductCode", szDevFactoryID));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
			httpPost.setEntity(uefEntity);
			// httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			CloseableHttpResponse response = client.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String retXml = EntityUtils.toString(entity, "UTF-8");
					int xmlPoint = retXml.indexOf("<?xml version");
					log.debug("Response content: " + retXml);
					szResult = getUsapRespcode(retXml.substring(xmlPoint));
				}
			} finally {
				response.close();
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (szResult == null)
			szResult = "FAIL.未知错误！";

		log.info(szResult);

		return szResult;
	}

	public String passwordCheck(String szTeller, String password) {
		String szResult = "";
		client = HttpClients.createDefault();
		httpPost = new HttpPost(abcConfig.getServicename());
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("ProtocalVersion", "V1.0.0"));
		nvps.add(new BasicNameValuePair("ProcessCode", "108"));
		nvps.add(new BasicNameValuePair("UserCode", convTeller(szTeller)));
		nvps.add(new BasicNameValuePair("AuthenticationType", "0"));
		nvps.add(new BasicNameValuePair("ClientUnique", abcConfig.getProgram()));
		nvps.add(new BasicNameValuePair("Token", password));
		nvps.add(new BasicNameValuePair("RandomCode", ""));
		nvps.add(new BasicNameValuePair("ForceLogin", "false"));
		nvps.add(new BasicNameValuePair("IdentitySN", ""));
		nvps.add(new BasicNameValuePair("CertSerial", ""));
		nvps.add(new BasicNameValuePair("ProductCode", ""));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
			httpPost.setEntity(uefEntity);
			// httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			CloseableHttpResponse response = client.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String retXml = EntityUtils.toString(entity, "UTF-8");
					int xmlPoint = retXml.indexOf("<?xml version");
					log.debug("Response content: " + retXml);
					szResult = getUsapRespcode(retXml.substring(xmlPoint));
				}
			} finally {
				response.close();
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (szResult == null)
			szResult = "FAIL.未知错误！";
		log.info(szResult);
		return szResult;
	}

}
